/* 
 * cms，一个基于J2EE架构内容管理系统
 * Copyright © GrayRabbit Co., Ltd. All rights reserved.
 * Department:运营department
 * 更多信息请访问：
 * http://code.google.com/p/gray-rabbit-cms/
 */
package org.grayrabbit.cms.action.system;

import java.util.List;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.grayrabbit.cms.action.common.BaseAction;
import org.grayrabbit.cms.constant.ConstantWebApp;
import org.grayrabbit.cms.constant.DictionaryStaticValues;
import org.grayrabbit.cms.entity.Admin;
import org.grayrabbit.cms.entity.Dictionary;
import org.grayrabbit.cms.entity.Role;
import org.grayrabbit.cms.service.system.RoleService;
import org.grayrabbit.cms.vo.system.RoleBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import org.grayrabbit.dao.util.Page;

/**
 * <b>RoleAction</b> Struts2 action�?





 * @version 1.0,创建时间:2011-05-16 15:55:03 
 */
@Controller
@Scope("prototype")
@Results( {
		@Result(name = "reload", type = "redirect", location = "role-list.action"),
		@Result(name = "input", type = "dispatcher", location = "role-input.jsp"),
		@Result(name = "success", type = "dispatcher", location = "role-list.jsp")
		}
		)
public class RoleAction extends BaseAction<RoleBean> {
	private static final long serialVersionUID = -1L;
	//Service接口接入
	@Autowired
	@Qualifier("roleServiceImpl")
	private RoleService roleService;
	//批量操作时使用的传入的ID
	private String ids;
	private List<Dictionary> isActive;
	//VO对象，由前端页面数据组装
	private RoleBean role;
	//分页对象
	private Page<Role> page = new Page<Role>(MAX_PAGE_NUM,true);
	/**
	 * 在执行（struts2的action调用时）list()方法前执行本方法
	 */
	public void prepareList(){
		prepareModel();
	}
	
	/**
	 * 在执行任何其它action方法（struts2的action调用时）前执行本方法
	 */
	public void prepare(){
		if(role==null){
			role = new RoleBean();
		}
	}
	
	@Override
	protected void prepareModel(){
		if(null!=role&&StringUtils.isNotBlank(role.getRoleId())){
			role = (RoleBean)dozer.map(roleService.getRole(role.getRoleId()),RoleBean.class);
		}
	}

	/**
	 * 删除<b>Role</b>记录的方法，成员变量<b>key</b>为主键的String数组，以主键方式进行删作
	 * 删除成功后，返回"reload"，然后跳转到role-list.action
	 */
	@Override
	@Action(value="role-delete")
	public String delete(){
		boolean deleteSuccess=false;
		String text=null;
		key=getBatchIds();
		try {
			if((role!=null)&&(StringUtils.isNotBlank(role.getRoleId()))){
				String[] str=new String[1];
				str[0]=role.getRoleId();
				deleteSuccess=roleService.delete(str);
			}else if(key!=null){
				deleteSuccess=roleService.delete(key);
			}
		} catch (Exception e) {
			log.debug("删除异常");
		}
		if(deleteSuccess){
			text=new String (this.getText("deleteSuccess"));
		}else{
			text=new String(this.getText("deleteFail"));
		}
		return renderText(text);
	}
	
	/**
	 * Role的列表方法，通过成员变量<b>page�?{insClassName}</b>调用service接口，更新page
	 * 执行成功后，将映射到role-list.jsp页面
	 */
	@Override
	@Action(value="role-list")
	public String list(){
		if(role!=null){
			if(("--").equals(role.getActive())){
				role.setActiveStatus(null);
			}else if("true".equals(role.getActive())){
				role.setActiveStatus(true);
			}else if("false".equals(role.getActive())){
				role.setActiveStatus(false);
			}
		}
		roleService.list(page,role);
		isActive = this.dictionaryService.getDictionaryListByTypeCode(DictionaryStaticValues.IS_ACTIVE);
		isActive = isActive==null?DictionaryStaticValues.EMPTY_DICTIONARY_LIST:isActive;
		return SUCCESS;
	}
	
	
	/**
	 * Role的新增与编辑的方法执行成功能
	 * 将映射到role-input.jsp
	 */
	@Action(value="role-input")
	public String input(){
		prepareModel();
		return INPUT;
	}
	
	/**
	 * save or update Role的方法，将成员property role转成Role实例，执行保存；
	 * 执行成功后，返回"reload"，然后跳转到role-list.action
	 */
	@Override
	@Action(value="role-save")
	public String save(){
		Role obj = (Role) dozer.map(role, Role.class);
		Admin currentAdmin=(Admin)getSessionValue(ConstantWebApp.CURRENT_ADMIN);
		//新建角色
		if(!StringUtils.isNotBlank(obj.getRoleId())){
			obj.setRoleId(null);
			obj.setActiveStatus(true);
			if(currentAdmin!=null){
				obj.setCreateLoginName(currentAdmin.getLoginName());
				obj.setCreateRealName(currentAdmin.getRealName());
				obj.setUpdateLoginName(currentAdmin.getLoginName());
				obj.setUpdateRealName(currentAdmin.getRealName());
			}
			obj.setCreateTime(new java.util.Date());
			obj.setUpdateTime(new java.util.Date());
		}
		//编辑角色
		if(null!=role&&StringUtils.isNotBlank(role.getRoleId())){
			if(currentAdmin!=null){
				obj.setUpdateLoginName(currentAdmin.getLoginName());
				obj.setUpdateRealName(currentAdmin.getRealName());
			}
			obj.setUpdateTime(new java.util.Date());
		}
		roleService.save(obj);
		return RELOAD;
	}
	
	/**
	 * 禁用/启用
	 * @return
	 */
	@Action(value="role-disableorenable"
	)
	public String disableOrEnable(){
			if((null!=role)&&(StringUtils.isNotBlank(role.getRoleId()))){
				roleService.disableOrEnable(role.getRoleId());
			}
		return RELOAD;
	}
	
	/**
	 * 角色状态批量修改
	 * @return
	 */
	@Action(value="role-activestatus"
	)
	public String roleActiveStatus(){
			if((role!=null)&&(role.getActiveStatus()!=null)){
				if(StringUtils.isNotBlank(role.getRoleId())){
					roleService.roleActiveStatus(role.getRoleId(),role.getActiveStatus());
				}else{
					String[] idBatchs=getBatchIds();
					roleService.roleActiveStatus(idBatchs,role.getActiveStatus());
				}
			}
		return RELOAD;
	}
	
	@Action(value="role-checkNameUnique")
	public String checkNameUnique(){
		String text="";
		try{
			if(role!=null){
				boolean unique=roleService.checkNameUnique(role.getRoleName().trim(),role.getRoleId());
				if(!unique){
					text="ok";
				}else{
					text="no";
				}
			}
		}catch(Exception e){
			text="no";
			log.debug("唯一性检查异常");
		}
		return renderText(text);
	}
	

	/**
	 * 反转禁用/启用状态
	 * @return
	 */
	public String getTurn(String key,String code){
		String activeStatus=this.getName(key, code);
		String text=null;
		if((StringUtils.isNotBlank(activeStatus))&&(("未激活").equals(activeStatus.trim()))){
			text=this.getText("enable");
		}else{
			text=this.getText("disable");
		}
		return text;
	}
	
	public String getTwoAdmin(Set<Admin> admins){
		String names="";
		int i=0;
		if(admins!=null){
			for(Admin a :admins){
				if((null!=a)&&(StringUtils.isNotBlank(a.getLoginName()))){
					if(i>=2)break;
					i++;
					if(!a.getActiveStatus()){
						names+="<font color='red'>"+a.getLoginName()+"</font>";
					}else{
						names+=a.getLoginName();						
					}
					
					
					if((i==1)&&(admins.size()>=2)){
						names+="、";
					}
				}
			}
		}
		return names;
	}
	public String getIds() {
		return ids;
	}

	public void setIds(String ids) {
		this.ids = ids;
	}
	
	/*
	 * return分页对象，默认实例化。如：page.pageNu=2,将更新相应的对象property
	 */
	public Page<Role> getPage() {
		return page;
	}
	//接收前端form,url提交参数组装成分页property
	public void setPage(Page<Role> page) {
		this.page = page;
	}
	
	/**return 前端页面数据组装VO对象,<b>RoleBean</b>*/
	public RoleBean getRole() {
		return role;
	}

	public void setRole(RoleBean role) {
		this.role = role;
	}
	
	public List<Dictionary> getIsActive() {
		return isActive;
	}

	public void setIsActive(List<Dictionary> isActive) {
		this.isActive = isActive;
	}
	private String[] getBatchIds(){
		String[] idBatchs=null;
		if(StringUtils.isNotBlank(ids)){
			if(ids.contains("on")){
				idBatchs=ids.substring(3).split("@");
			}else{
				idBatchs=ids.split("@");
			}
		}
		return idBatchs;
	}
	/**
	 * 实现ModelDriven的接口简例前端页的bean组装写法,
	 *  如：
	 *	<pre>
	 *		<code> name="user.userName"</code>
	 *	改写成：
	 *		<code> name="userName"</code>
	 *	action实例中，会自动组成user成员变量
	 *	</pre>
	 */
	public RoleBean getModel() {
		return role;
	}
}